package com.iwown.sample4GApi.calculation;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.iwown.sample4GApi.protobuf.ACCelerometerData;
import com.iwown.sample4GApi.protobuf.HisDataOuterClass;
import com.iwown.sample4GApi.utils.MyDateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class AccPreprocessor {
    private static final Logger log = LoggerFactory.getLogger(AccPreprocessor.class);

    public void DataPrepare(byte[] payload) {
        HisDataOuterClass.HisNotification hisNotify = null;
        try {
            hisNotify = HisDataOuterClass.HisNotification.parseFrom(payload);
        } catch (InvalidProtocolBufferException ex) {
            ex.printStackTrace();
            return;
        }
        if(hisNotify.hasHisData()){
            HisDataOuterClass.HisData hisData = hisNotify.getHisData();
            if(hisData.hasACCelerometerData()){
                ACCelerometerData.HisACCelerometer accPb = hisData.getACCelerometerData();
                ByteString xBstr = accPb.getAccX();
                ByteString yBstr = accPb.getAccY();
                ByteString zBstr = accPb.getAccZ();

                if(xBstr.isEmpty() || yBstr.isEmpty() || zBstr.isEmpty()){
                    log.error("x/y/z data is empty");
                    return;
                }

                List<Integer> xList = new ArrayList<>();
                List<Integer> yList = new ArrayList<>();
                List<Integer> zList = new ArrayList<>();

                byte[] xbuffer = xBstr.toByteArray();
                for(int j=1;j<xbuffer.length;j=j+2){
                    byte low = (byte)xbuffer[j-1];
                    int high = (int)(xbuffer[j]<<8);
                    int real = low+high;
                    xList.add(real);
                }

                byte[] ybuffer = yBstr.toByteArray();
                for(int j=1;j<ybuffer.length;j=j+2){
                    byte low = (byte)ybuffer[j-1];
                    int high = (int)(ybuffer[j]<<8);
                    int real = low+high;
                    yList.add(real);
                }

                byte[] zbuffer = zBstr.toByteArray();
                for(int j=1;j<zbuffer.length;j=j+2){
                    byte low = (byte)zbuffer[j-1];
                    int high = (int)(zbuffer[j]<<8);
                    int real = low+high;
                    zList.add(real);
                }
                /*
                	this is raw data of one minute, combine data of expected time range, to invoke calculation api
                */
                String data_time = MyDateTimeUtils.convert2DateTimeString(accPb.getTimeStamp().getDateTime().getSeconds());
                log.info(String.format("%s x:%d,y:%d,z:%d",data_time,xList.size(),yList.size(),zList.size()));
            }
        }
    }
}
